package org.ghost.wechat.platform.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.ghost.wechat.platform.common.enumeration.WeChatErrorCodeEnum;
import org.ghost.wechat.platform.common.http.HttpClientFactory;
import org.ghost.wechat.platform.dao.IWeChatMessageDAO;
import org.ghost.wechat.platform.dao.IWeChatWebDAO;
import org.ghost.wechat.platform.dto.wechat.message.WeChatMsgSendRspDTO;
import org.ghost.wechat.platform.dto.wechat.message.WeChatMsgTemplateDTO;
import org.ghost.wechat.platform.dto.wechat.web.WeChatOpenIdRspDTO;
import org.ghost.wechat.platform.enumeration.WechatGrantTypeEnum;
import org.ghost.wechat.platform.service.IWeChatWebService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;

/**
 * @author 01
 */
@Service
public class WeChatWebServiceImpl extends AbstractServiceImpl implements IWeChatWebService {
    private static final Logger logger = LoggerFactory.getLogger(WeChatWebServiceImpl.class);

    private IWeChatWebDAO weChatWebDAO = HttpClientFactory.getBean(IWeChatWebDAO.class);
    private IWeChatMessageDAO weChatMessageDAO = HttpClientFactory.getBean(IWeChatMessageDAO.class);

    @Override
    public String getAuthorizeUrl(String appId, String redirectUri, String responseType, String scope, String state) {
        return MessageFormat.format("{0}?appid={1}&redirect_uri={2}&response_type={3}&scope={4}&state={5}#wechat_redirect",
                "https://open.weixin.qq.com/connect/oauth2/authorize",
                StringUtils.trim(appId),
                StringUtils.trim(redirectUri),
                StringUtils.trim(responseType),
                StringUtils.trim(scope),
                StringUtils.trim(state));
    }

    @Override
    public WeChatOpenIdRspDTO getOpenId(String appId, String secret, String code) {
        if (StringUtils.isNotBlank(appId) && StringUtils.isNotBlank(secret) && StringUtils.isNotBlank(code)) {
            return this.weChatWebDAO.getOpenId(appId, secret, code, WechatGrantTypeEnum.AUTHORIZATION_CODE.getCode());
        }
        return null;
    }

    @Override
    public WeChatMsgSendRspDTO sendTemplateMessage(String token, WeChatMsgTemplateDTO msgTemplateDTO) {
        if (StringUtils.isNotBlank(token) && msgTemplateDTO != null) {
            String accessToken = this.getAccessToken(token);
            WeChatMsgSendRspDTO wechatMsgSendRspDTO = this.weChatMessageDAO.sendTemplateMessage(accessToken, msgTemplateDTO);
            //特殊错误码处理
            if (wechatMsgSendRspDTO != null && WeChatErrorCodeEnum.checkAccessToken("" + wechatMsgSendRspDTO.getErrCode())) {
                accessToken = this.getAccessToken(token, true, accessToken);
                return this.weChatMessageDAO.sendTemplateMessage(accessToken, msgTemplateDTO);
            }
        }
        return null;
    }
}
